package com.yjps.house.service;


import com.yjps.common.dao.AddressDao;
import com.yjps.common.model.Address;
import com.yjps.house.dao.HistoryDao;
import com.yjps.house.dao.HouseDao;
import com.yjps.house.model.House;
import com.yjps.house.model.PublishHistory;
import com.yjps.house.model.RecommendedHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


@Service("houseService")
public class HouseService {

    @Autowired
    private HouseDao houseDao;

    @Autowired
    private HistoryDao historyDao;

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private HistoryService historyService;

    /**
     * @param house
     */
    @Transactional
    public boolean updatehouse(House house) {
//        House localHouse = houseDao.get(house.getId());
//        if (localHouse.getIsAuthentication() == 1 ||
//                localHouse.getIsBoutique() == 1 || localHouse.getIsValid() == 0) {
//            return false;
//        }

        String hql="update House h set h.buildingId = :buildingId , h.title = :title," +
                "h.description= :description, h.imageUrl= :imageUrl, h.area = :area," +
                "h.price = :price, h.sellType = :sellType,h.state =:state, h.detail = :detail, " +
                "h.isBoutique =:isBoutique ,h.isAuthentication =:isAuthentication, h.type =:type, " +
                "h.isValid =:isValid ,h.remark =:remark where h.id = :id";

        Map<String,Object> params = new HashMap<>();
        params.put("buildingId",house.getBuildingId());
        params.put("title",house.getTitle());
        params.put("description",house.getDescription());
        params.put("imageUrl",house.getImageUrl());
        params.put("area",house.getArea());
        params.put("price",house.getPrice());
        params.put("sellType",house.getSellType());
        params.put("state", house.getState());
        params.put("detail",house.getDetail());
        params.put("isBoutique", house.getIsBoutique());
        params.put("isAuthentication", house.getIsAuthentication());
        params.put("type", house.getType());
        params.put("isValid",house.getIsValid());
        params.put("remark", house.getRemark());
        params.put("id", house.getId());
        int affectRows=historyDao.excute(hql,params);
        if (affectRows==0){
            return false;
        }
        return true;
    }

    /**
     *
     *
     * @param houseId
     * @param time
     * @param result
     * @return
     */
    @Transactional
    public boolean verfiyHouse(int houseId, String time, int result) {
        String hql = "from PublishHistory p where p.houseId =:houseId";
        Map<String, Object> map = new HashMap<>();
        map.put("houseId", houseId);
        List<PublishHistory> phs = historyDao.find(hql, map);
        PublishHistory history = phs.get(0);


        if (history.getIsValid() == 0) {
            return false;
        }

        history.setHandleResult(result);
        history.setHandleTime(time);
        historyService.updatePublishHistory(history);

        House house = houseDao.get(houseId);
        house.setState(result);

        String hql2="update House h set h.state = :state "+
                "where h.id = :id";
        Map<String,Object> params = new HashMap<>();
        params.put("state", house.getState());
        params.put("id", house.getId());
        historyDao.excute(hql2,params);
        return true;
    }


    /**

     *
     * @param houseId
     * @param time
     * @param result
     * @return
     */
    @Transactional
    public boolean recommendHouse(int houseId, String time, int result) {
        String hql = "from t_house_recommend_history p where p.house_id =: houseId";
        Map<String, Object> map = new HashMap<>();
        map.put("houseId", houseId);
        List<RecommendedHistory> rhs = historyDao.find(hql, map);
        RecommendedHistory rh = rhs.get(0);


        if (rh.getIsValid() == 0) {
            return false;
        }

        rh.setHandleResult(result);
        rh.setTime(time);
        historyDao.update(rh);

        House house = houseDao.get(houseId);
        house.setIsBoutique(result);
        String hql2="update House h set h.state = :state "+
                "where h.id = :id";
        Map<String,Object> params = new HashMap<>();
        params.put("state", house.getState());
        params.put("id", house.getId());
        historyDao.excute(hql2, params);
        return true;
    }

    /**
     *
     * {
     * "address": {
     * "province": "",
     * "city": "",
     * "county": "",
     * "town": ""
     * },
     * "house": {
     * "area ": "",
     * "sellType ": "",
     * "isBoutique ": "1",
     * "isAuthentication": "",
     * "type": "",
     * "price": ""
     * },
     * "page": "",
     * "size": ""
     * }
     *
     * @param houseMap
     * @param addressMap
     * @return
     */
    public List<House> queryHouse(Map<String, Object> houseMap, Map<String, Object> addressMap) {

        String hql = "from House where valid=1 and state=1";
        for (String key : houseMap.keySet()) {
            //if(houseMap.get(key) instanceof String){
            String value = (String) houseMap.get(key);
            if (!"".equals(value)) {
                if ("area".equals(key) || "price".equals(key)) {
                    String[] str = value.split("-");
                    String min = str[0];
                    String max = str[1];
                    hql = hql + " and " + key + " between " + min + " and " + max;
                } else {
                    hql = hql + " and " + key + "=" + houseMap.get(key);
                }

            }
            //}
        }

        List<House> houseList = houseDao.find(hql);


        Iterator<House> iter = houseList.iterator();
        while (iter.hasNext()) {
            House house = iter.next();
            String hql2 = "from Address a where a.id in " +
                    "(select b.addressId from Building b where b.id =:buildingId)";
            Map<String, Object> map = new HashMap<>();
            map.put("buildingId", house.getBuildingId());
            Address address = addressDao.findUniqueResult(hql2, map);
            if (!compare(address, addressMap)) {
                iter.remove();
            }
        }

        return houseList;
    }

    /**
     * 获取返回列表的页数
     * @param houseList
     * @param pageSize
     * @return
     */
    public int getPages(List<House> houseList,int pageSize){
        int size=houseList.size();
        if (size%pageSize==0){
            return size/pageSize;
        }
        return (size/pageSize)+1;
    }

    /**
     * 列表分页
     * @param houseList
     * @param startRow
     * @param pageSize
     * @return
     */
    public List<House> subList(List<House> houseList,int startRow,int pageSize){
        if (houseList.size()<pageSize){
            return houseList;
        }
        if ((houseList.size())<=(pageSize+startRow)){
            return houseList.subList(startRow,houseList.size());
        }

        return houseList.subList(startRow,startRow+pageSize);
    }


    public boolean compare(Address address, Map<String, Object> addressMap) {
        String cityCondition = (String) addressMap.get("city");
        String countyCondition = (String) addressMap.get("county");
        String townCondition = (String) addressMap.get("town");
        String city = address.getCity();
        String county = address.getCounty();
        String town = address.getTown();
        boolean flag = true;
        if ("".equals(cityCondition)) {
            return flag;
        } else if (city.equals(cityCondition)) {

            if ("".equals(countyCondition)) {
                return flag;
            }

            if (county.equals(countyCondition)) {

                if ("".equals(townCondition)) {
                    return flag;
                }

                if (town.equals(townCondition)) {
                    return flag;
                }else{
                    return false;
                }
            }else {
                return  false;
            }
        }else {
            return false;
        }
    }

}